package org.weso.acota.dao;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.junit.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.traversal.NodeIterator;
import org.weso.acota.to.RequestSuggestionTO;
import org.weso.acota.to.ResourceTO;
import org.weso.acota.to.SuggestionTO;
import org.weso.acota.utils.DocumentBuilderHelper;

public class NLPEvaluation {

	@SuppressWarnings({ "rawtypes", "unused" })
	@Test
    public void suggestEvaluation() throws Exception {
		long tiempoInicio = System.currentTimeMillis();
		InputStream doc = getClass().getClassLoader().getResourceAsStream("org/weso/acota/loader/news.xml"); 
		Document newsXML = DocumentBuilderHelper.getDocumentFromInputStream(doc);
		 NodeIterator it;
		 //Extract the id of new
		 it = org.apache.xpath.XPathAPI.selectNodeIterator(newsXML, "//@id");
		 Node n = it.nextNode();
		 int total=0;
		 int totalAnalyzed=0;
		 int disminuciones=0;
         while(n != null){
        	 if(total>0 && total < 2){
             String descripction;
        	 String label;
        	 String url;
        	 String tags;
        	 String[] tagsList;
         	//Extract tittle of each new and save in a label variable
         	NodeIterator titleNode = org.apache.xpath.XPathAPI.selectNodeIterator(newsXML, "//new[@id='"+n.getNodeValue()+"']/title/text()");
         	try {
         		label = titleNode.nextNode().getNodeValue();
			} catch (Exception e) {
				label ="";
			}
         	
         	//Extract description of each new and save in a description variable
         	NodeIterator descriptionNode = org.apache.xpath.XPathAPI.selectNodeIterator(newsXML, "//new[@id='"+n.getNodeValue()+"']/comment/text()");
         	try {
         		descripction = descriptionNode.nextNode().getNodeValue();
			} catch (Exception e) {
				descripction ="";
			}
			
			//Extract url of each new and save in a description variable
         	NodeIterator urlNode = org.apache.xpath.XPathAPI.selectNodeIterator(newsXML, "//new[@id='"+n.getNodeValue()+"']/url/text()");
         	try {
         		url = urlNode.nextNode().getNodeValue();
			} catch (Exception e) {
				url ="";
			}
			
			//Extract tag's of each new and save in a description variable
         	NodeIterator tagNode = org.apache.xpath.XPathAPI.selectNodeIterator(newsXML, "//new[@id='"+n.getNodeValue()+"']/keywords/text()");
         	try {
         		tags = tagNode.nextNode().getNodeValue();
			} catch (Exception e) {
				tags ="";
			}
			tagsList = tags.split(",");
			
			//Create the resource object
			ResourceTO resource = new ResourceTO();
			resource.setLabel(label);
			resource.setDescription(descripction);
			resource.setUri(url);
			
			//Create the request
			RequestSuggestionTO request = new RequestSuggestionTO(resource);
			
			//previous analisys by lucene
			SuggestDAO suggestLucene = new SuggestLuceneDAOImpl();
			SuggestionTO suggestPrevious = OderedSuggestion(suggestLucene.suggest(request));
			request.setSuggestions(suggestPrevious);
			int tagsByLucene = suggestPrevious.getLabels().size();
			System.out.println("********LUCENE*******("+tagsByLucene+")- "+total);
         	Iterator itrLucene = suggestPrevious .getLabels().entrySet().iterator();
    		while (itrLucene.hasNext()) {
    			Map.Entry e = (Map.Entry)itrLucene.next();
    			System.out.println(""+e.getKey()+";"+e.getValue()+"");
    		}
			
			
			//analisys by openNLP
			SuggestDAO nplDAO = new SuggestNplDAOImpl();
			SuggestionTO suggestFinal = OderedSuggestion(nplDAO.suggest(request));
			int tagsByOpenNLP = suggestPrevious.getLabels().size();
			//Print results
			System.out.println("********openNLP ("+tagsByOpenNLP+")*******");
         	Iterator itr = suggestFinal .getLabels().entrySet().iterator();
    		while (itr.hasNext()) {
    			Map.Entry e = (Map.Entry)itr.next();
    			System.out.println(""+e.getKey()+";"+e.getValue()+"");
    		}
         	if(tagsByLucene> tagsByOpenNLP){
         		disminuciones++;
         	}
         	totalAnalyzed++;
         	}
         	total++;
         	n = it.nextNode();
         }
         long totalTiempo = System.currentTimeMillis() - tiempoInicio;
         System.out.println("Disminuciones"+disminuciones);
         System.out.println("Runtime :" + totalTiempo + " miliseg");
        /* System.out.println("\n*****Totals********\n");
         System.out.println("Total of resourses:"+totalAnalyzed+"\n");
         System.out.println("Total appears:"+appearsGeneral+"\n");
        */
    }
	
	@SuppressWarnings("unchecked")
	public SuggestionTO OderedSuggestion(SuggestionTO suggest){
		//order suggestions
		LinkedHashMap <String,Integer> labels = (LinkedHashMap<String, Integer>) suggest.getLabels();
		//sorted map
		LinkedHashMap <String,Integer> orderLabels = new LinkedHashMap<String, Integer>();
		//characters of tags - labels
		@SuppressWarnings("rawtypes")
		List values = new ArrayList<Integer>(labels.values());
		//ordered set
		Collections.sort(values);
		int tmp=0;
		for (int i= values.size()-1; i>=0;i--){
			tmp = (Integer) values.get(i);
			for( @SuppressWarnings("rawtypes") Map.Entry k : labels.entrySet())
			{
				int valueLabel = (Integer) k.getValue();
				if(tmp == valueLabel )
				{
					orderLabels.put((String) k.getKey(), (Integer) k.getValue());
				}
			}
		}	
		suggest.setLabels(orderLabels);
		return suggest;
    }
	
}     

